import React, { useCallback, useEffect } from 'react';
import {
  Alert,
  InteractionManager,
  Keyboard,
  Linking,
  Platform,
  Pressable,
  StyleSheet,
  View,
} from 'react-native';
import { useTranslation } from 'react-i18next';
import { useLayoutEffect, useRef, useState } from 'react';
import ScannerOverlay from './ScannerOverlay';
import { launchImageLibrary } from 'react-native-image-picker';
import NativeScan from '~/specs/NativeScan';
import { deviceApi, DeviceCategoryModel } from '@/services/api/deviceApi';
import {
  SafeAreaView,
  useSafeAreaInsets,
} from 'react-native-safe-area-context';
import { t } from 'i18next';
import Toast from '@/utils/toast';
import { useAppTheme, Icon, TextInput, Button, Text } from 'tsun-smart-ui';
import { ErrorText } from '@/components/ErrorText';
import { useForm, Controller } from 'react-hook-form';
import toast from '@/utils/toast';
import { KeyboardAwareScrollView } from 'react-native-keyboard-controller';
import { RouteProp, useNavigation, useRoute } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { StationDTO } from '@/services/api/stationApi';
import eventBus from '@/utils/eventBus';
import NativeToast from '~/specs/NativeToast';
import { PERMISSIONS, RESULTS } from 'react-native-permissions';
import PermissionUtils from '@/utils/PermissionUtils';
import { useDebounceFn } from 'ahooks';

export const ScanCode = () => {
  const navigation = useNavigation<NativeStackNavigationProp<any>>();
  const route = useRoute<RouteProp<any>>();
  const setupNetworkOnly = route.params?.setupNetworkOnly ?? false;
  const [open, setOpen] = useState(false);
  const theme = useAppTheme();
  const cameraRef = useRef<{
    setOpen: (open: 'on' | 'off') => void;
  }>(null);
  const { top } = useSafeAreaInsets();

  useEffect(() => {
    PermissionUtils.checkPermission(PERMISSIONS.IOS.CAMERA).then((value) => {
      if (!value.granted) {
        PermissionUtils.showPermissionNotGrantedAlert();
      }
    });
  }, []);

  useLayoutEffect(() => {
    if (open) {
      cameraRef.current?.setOpen('on');
    } else {
      cameraRef.current?.setOpen('off');
    }
  }, [open]);
  useEffect(() => {
    const unsubscribe = navigation.addListener('blur', () => {
      setOpen(false);
    });
    return unsubscribe;
  }, [navigation]);

  const { run: debounceRecognize } = useDebounceFn(
    () => onRecognizeLocalImage(),
    { wait: 300 }
  );

  const onRecognizeLocalImage = useCallback(async () => {
    const permissionResult = await PermissionUtils.checkPermission(
      PERMISSIONS.IOS.PHOTO_LIBRARY
    );
    if (permissionResult.status === RESULTS.DENIED) {
      PermissionUtils.showPermissionNotGrantedAlert();
      return;
    }
    launchImageLibrary({
      mediaType: 'photo',
      quality: 1,
      includeBase64: true,
      includeExtra: true,
    }).then((value) => {
      if (value?.errorCode === 'permission') {
        // setPermissionDialogOpen(true);
      } else if (value.assets?.[0].uri) {
        NativeScan.scanBarcodeFromImage(
          Platform.OS === 'ios' ? value.assets[0].uri : value.assets[0].base64!
        )
          .then((code) => {
            if (setupNetworkOnly) {
              navigation.navigate('SetupDeviceNetwork', { snCode: code });
            } else {
              navigation.navigate('SNCode', { code });
            }
          })
          .catch((e) => {
            console.log(e);
            toast.error({
              message: t('common.scan.tip'),
            });
          });
      }
    });
  }, [setupNetworkOnly]);

  return (
    <View style={[styles.container]}>
      <ScannerOverlay ref={cameraRef} />
      <Pressable
        className=" absolute"
        style={{
          marginTop: top + 12,
          padding: 16,
        }}
        onPress={() => {
          navigation.goBack();
        }}
      >
        <Icon name="back" size={20} color={'#fff'}></Icon>
      </Pressable>

      <View className="absolute bottom-12 w-full gap-6" key={'底部按钮'}>
        <View className="justify-center items-center">
          <VerticalButton
            title={
              !open ? t('scan.turnon.flashlight') : t('scan.turnoff.flashlight')
            }
            iconName={open ? 'flashlight' : 'flashlight-off'}
            iconColor={open ? theme.colors?.brand?.primary : '#fff'}
            iconSize={32}
            backgroundColor={'transparent'}
            onPress={() => setOpen(!open)}
          />
        </View>

        <View className="flex-row justify-around">
          <VerticalButton
            title={t('sys.app.album')}
            iconName="image"
            onPress={debounceRecognize}
          />
          <VerticalButton
            title={t('password.serial.number')}
            iconName="edit"
            onPress={() => {
              navigation.navigate({
                name: 'SNCode',
                params: {
                  category: route.params?.category,
                  station: route.params?.station,
                  setupNetworkOnly,
                },
              });
            }}
          />
          <VerticalButton
            title={t('sys.app.discover.devices')}
            iconName="equipment-fill"
            iconSize={28}
            onPress={() =>
              navigation.navigate('DiscoverDevices', {
                category: route.params?.category,
                station: route.params?.station,
                setupNetworkOnly: setupNetworkOnly,
              })
            }
          />
        </View>
      </View>
    </View>
  );
};

type VerticalButtonProps = {
  onPress: () => void;
  title: string;
  iconName: string;
  iconColor?: string;
  iconSize?: number;
  backgroundColor?: string;
};

const VerticalButton: React.FC<VerticalButtonProps> = React.memo((props) => {
  const iconColor = props.iconColor ?? '#FFF';
  const iconSize = props.iconSize ?? 48;
  const backgroundColor = props.backgroundColor ?? styles.icon.backgroundColor;
  return (
    <Pressable
      onPress={props.onPress}
      className="rounded-full p-2.5 gap-y-2 justify-center items-center min-w-[110px]"
    >
      <View
        className=" items-center justify-center  size-12 rounded-full"
        style={{ backgroundColor: backgroundColor }}
      >
        <Icon
          name={props.iconName}
          className="text-center"
          size={iconSize}
          color={iconColor}
        ></Icon>
      </View>

      <Text
        className="  min-w-[90px] text-center"
        style={{
          color: '#fff',
        }}
      >
        {props.title}
      </Text>
    </Pressable>
  );
});

interface FormData {
  code: string;
  name: string;
}

export const SNCode = () => {
  const route = useRoute<RouteProp<any>>();
  const code: string | undefined = route.params?.code;
  const deviceCategory: DeviceCategoryModel | undefined =
    route.params?.category;
  const setupNetworkOnly = route.params?.setupNetworkOnly ?? false;
  const navigation = useNavigation<NativeStackNavigationProp<any>>();
  const { t } = useTranslation();
  const { bottom } = useSafeAreaInsets();
  const [loading, setLoading] = useState(false);
  const {
    control,
    handleSubmit,
    formState: { errors },
  } = useForm<FormData>({
    defaultValues: {
      code: route.params?.code ?? '',
      name: '',
    },
  });
  const isWiFiCategory =
    deviceCategory?.networkType.toLowerCase().startsWith('wifi') ?? false;

  const shouldSetupDeviceNetwork = isWiFiCategory || setupNetworkOnly;

  // 处理提交
  const onSubmit = async (
    formData: FormData,
    action: 'finish' | 'setup-network'
  ) => {
    try {
      if (setupNetworkOnly) {
        navigation.navigate('SetupDeviceNetwork', {
          category: route.params?.category,
          station: route.params?.station,
          snCode: formData.code,
          setupNetworkOnly,
        });
        return;
      }
      setLoading(true);
      Keyboard.dismiss();
      NativeToast.makeToastActivity();
      // 检查SN码是否存在
      const { data: isExist } = await deviceApi.checkSNCode({
        deviceSn: formData.code,
      });
      if (isExist) {
        Toast.error({
          message: t('password.alreadyExists', {
            defaultValue: 'SN序列号已存在',
          }),
        });
        setLoading(false);
        NativeToast.hideToastActivity();
        return;
      }

      const station: StationDTO | undefined = route.params?.station;
      // 添加设备
      deviceApi
        .addDevice({
          deviceSn: formData.code,
          deviceName: formData.name,
          stationId: station?.id,
          coverImage: deviceCategory?.mainImage!,
          categoryId: Number(deviceCategory?.id!),
        })
        .then((res) => {
          NativeToast.hideToastActivity();
          Toast.success({
            message: t('common.addSuccessText', { defaultValue: '添加成功' }),
          });

          if (action === 'setup-network') {
            navigation.navigate('SetupDeviceNetwork', {
              category: route.params?.category,
              station: route.params?.station,
              snCode: formData.code,
              snName: formData.name,
            });
          } else {
            eventBus.emit('DEVICE_CHANGE');
            navigation.popToTop();
          }
        })
        .catch((reason) => {
          NativeToast.hideToastActivity();
        });
    } finally {
      setLoading(false);
      NativeToast.hideToastActivity();
    }
  };

  return (
    <View className="flex-1">
      <KeyboardAwareScrollView
        className="flex-1 px-4 mt-[22]"
        contentContainerStyle={{
          justifyContent: 'space-between',
          flex: 1,
        }}
        style={{
          paddingBottom: bottom || 24,
        }}
      >
        <View style={[styles.formContainer]}>
          {/* SN码输入框 */}
          <View className="mb-[10]">
            <Controller
              control={control}
              name="code"
              rules={{
                required: t('password.enter.sn.serial.number', {
                  defaultValue: '请输入SN序列号',
                }),
                pattern: {
                  value: /^[a-zA-Z0-9_-]{2,20}$/,
                  message: t('common.content.tip', {
                    defaultValue: 'SN序列号不能包含空格',
                  }),
                },
              }}
              render={({ field: { onChange, value } }) => (
                <TextInput
                  value={value}
                  label={t('password.serial.number')}
                  editable={!code}
                  placeholder={t('password.enter.sn.serial.number')}
                  onChangeText={onChange}
                  maxLength={20}
                  returnKeyType="next"
                  enterKeyHint="next"
                />
              )}
            />
            <View className="pt-2 ml-4">
              {errors.code && <ErrorText text={errors.code.message!} />}
            </View>
          </View>
          {!setupNetworkOnly && (
            <Controller
              control={control}
              name="name"
              rules={{
                required: t('password.Input.device.name', {
                  defaultValue: '请输入设备名称',
                }),
                pattern: {
                  value: /^\S*$/,
                  message: t('validation.no.spaces.allowed', {
                    defaultValue: '设备名称不能包含空格',
                  }),
                },
              }}
              render={({ field: { onChange, value } }) => (
                <TextInput
                  value={value}
                  label={t('device.name')}
                  placeholder={t('password.Input.device.name')}
                  onChangeText={onChange}
                  returnKeyType="done"
                  enterKeyHint="done"
                />
              )}
            />
          )}
          <View className="pt-2 ml-4">
            {errors.name && <ErrorText text={errors.name.message!} />}
          </View>

          {/* 提交按钮 */}
        </View>
      </KeyboardAwareScrollView>
      <SafeAreaView
        edges={['left', 'right', 'bottom']}
        className="bg-text6 px-4 py-2 gap-3"
      >
        {!setupNetworkOnly && (
          <Button
            // loading={loading}
            title={t('common.add.device')}
            disabled={loading}
            onPress={handleSubmit((data) => onSubmit(data, 'finish'))}
          />
        )}
        {shouldSetupDeviceNetwork && (
          <Button
            // loading={loading}
            title={t('sys.app.add.and.setup.network')}
            disabled={loading}
            onPress={handleSubmit((data) => onSubmit(data, 'setup-network'))}
          />
        )}
      </SafeAreaView>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  formContainer: {
    flex: 1,
  },
  input: {
    marginBottom: 8,
    height: 40,
    borderRadius: 20,
  },
  button: {
    marginTop: 24,
    height: 40,
    justifyContent: 'center',
    borderRadius: 20,
  },
  icon: {
    backgroundColor: 'rgba(255, 255, 255, 0.32)',
  },
});
